import router from './router/index'
import { store } from './store'
// import { useStore } from './store'
// import { useStore } from 'vuex'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { forEach, isEmpty, filter } from 'lodash'
import { dyncRoutes } from './utils/routes'
// import { loadView, filterAsyncRouter } from '@/utils/router'
// import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// NProgress.configure({ showSpinner: false })
// const router = useRouter()
const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

function handleDyncRoutes(path) {
  return new Promise((resolve, reject) => {
    // console.log(store.getters.roles.length, 'roles.length')
    store
      .dispatch('GenerateRoutes')
      .then((accessRoutes) => {
        console.log(accessRoutes, 'router.getRoutes()')
        if (!accessRoutes.length) {
          ElMessage({
            message: '该用户没有任何菜单权限！',
            type: 'warning',
          })
          localStorage.removeItem('account')
          localStorage.removeItem('token')
          localStorage.removeItem('routes')
          localStorage.removeItem('permissions')
          store.state.router.routes = []
          router.push('/login')
          return
        }
        // 根据roles权限生成可访问的路由表
        forEach(accessRoutes, (route) => {
          router.addRoute('home', route) // 动态添加可访问路由表
        })
        router.push(path)
        resolve(path)
      })
      .catch((error) => {
        console.error(error)
        reject(false)
      })
    resolve(true)
    // if (store.getters.roles.length !== 0) {
    // } else {
    //   // 判断当前用户是否已拉取完user_info信息
    //   store.dispatch('GetUserInfo').then(res => {
    //     // 拉取user_info
    //     const roles = res.data.roles
    //   })
    // }
  })
}

export function handlePermission() {
  router.beforeEach(async (to) => {
    // NProgress.start()
    if (to.path == '/outLogin'||to.path == '/login') {
      return true
    }
    if (getToken()) {
      /* has token*/
      if (to.path === '/login') {
        // NProgress.done()
        // return '/'
      } else {
        // if (isEmpty(store.state.router.routes)) {
        //   return (await handleDyncRoutes(to)) as Promise<any>
        // } else {
        //   return true
        // }
      }
    } else {
      // 没有token
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        return true
      } else {
        // NProgress.done()
        return `/login?redirect=${to.path}`
      }
    }
  })
  router.afterEach(() => {
    // NProgress.done()
  })
}
